package com.autumn.platform.core.logger.impl;

import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.slf4j.event.Level;

import com.autumn.platform.core.Utils;
import com.autumn.platform.core.logger.LogLevelUpdater;

public class Log4jLevelUpdater implements LogLevelUpdater {

    @Override
    public void update(String prefix, Level level) {
        boolean noPrefix = Utils.isBlank(prefix);
        @SuppressWarnings("rawtypes")
        Enumeration enumeration = LogManager.getCurrentLoggers();
        org.apache.log4j.Level newLevel = convertLevel(level);
        while (enumeration.hasMoreElements()) {
            Logger logger = (Logger) enumeration.nextElement();
            if (noPrefix || logger.getName().startsWith(prefix)) {
                logger.setLevel(newLevel);
            }
        }
    }

    @Override
    public void set(String name, Level level) {
        LogManager.getLogger(name).setLevel(convertLevel(level));
    }

    @Override
    public Set<String> getLogNames() {
        @SuppressWarnings("rawtypes")
        Enumeration enumeration = LogManager.getCurrentLoggers();
        Set<String> names = new LinkedHashSet<>();
        while (enumeration.hasMoreElements()) {
            Logger logger = (Logger) enumeration.nextElement();
            names.add(logger.getName());
        }
        return names;
    }

    @Override
    public void setRootLevel(Level level) {
        LogManager.getRootLogger().setLevel(this.convertLevel(level));
    }

    /**
     * @param level
     * @return
     */
    private org.apache.log4j.Level convertLevel(Level level) {
        org.apache.log4j.Level newLevel = org.apache.log4j.Level.toLevel(level.toString());
        return newLevel;
    }
}
